package ferp.core.ai.filter;

import ferp.core.card.Card;
import ferp.core.game.Game;
import ferp.core.player.Hand;

/**
 * User: igorgok
 * Date: 9/9/12 4:53 PM
 */
public class FilterDeclarerFirstHandMove
{
  public static int apply(int candidates, Card.Suit trump, int declarer, int[] hands)
  {
    int filtered = 0;

    // get trump suit
    int t = Hand.get(candidates, trump);
    int tl = Card.Suit.length(t);

    // resolve opponents and their trump suits
    int p1 = Game.next(declarer);
    int t1 = Hand.get(hands[p1], trump);

    int p2 = Game.next(p1);
    int t2 = Hand.get(hands[p2], trump);

    if (tl > 0)
    {
      // if declarer has trump cards but opponents don't then all trump candidates can be removed
      if (Card.Suit.length(t1) + Card.Suit.length(t2) == 0)
        filtered = Hand.remove(candidates, trump);
      else
      {
        // if declarer has ace and total amount of trump cards is at least 5 the first move could be made with ace -
        // this is a first move to check how trump cards were dealt between opponents
        if (Hand.contains(t, Card.Mask.ACE) && (tl > 4 || (Hand.contains(t, Card.Mask.KING) && tl > 3)))
          filtered = Hand.add(0, trump, Card.Rank.ACE);
        else
          if (canMoveWithHighestTrump(t, t1, t2))
            filtered = Hand.add(0, trump, Card.Set.highest(t));
      }
    }

    return filtered == 0 ? candidates : filtered;
  }

  private static boolean canMoveWithHighestTrump(int t, int t1, int t2)
  {
    // virtual shared hand of both opponents
    int to = Hand.add(t1, Hand.add(0, t2));

    while (t != 0 && to != 0)
    {
      Card.Rank h  = Card.Set.highest(t);
      Card.Rank ho = Card.Set.higher(to, h); Card.Rank lo = Card.Set.lowest(to);

      if (ho != null)
        return false;

      t  = Hand.remove(t, h.hash());
      to = Hand.remove(to, lo.hash());
    }

    return true;
  }
}
